<?php

/**
 * Description of ShoppingCart
 *
 * @author NE
 */
class RCMS_Object_Shopping_ShoppingCart {

	private $_cartItems = array();

	private $_session = null;

	private $_totalPrice = 0;

    private $_totalWeight = 0;

	public function __construct() {
		if(null === $this->_session) {
			$this->_session = new Zend_Session_Namespace('ShoppingCart');
		}
		//$this->_session->toasterShopingCartItems = '';
		$this->_load();
	}

	/**
	 * Add item to cart
	 *
	 * @param array $item array('id' => 1, 'options' => array('size' => 'M', 'color' => 'pink'), 'qty' => 1)
	 */
	public function addItem(array $item) {
		$this->_load();
		$itemKey = $this->_getItemKey($item['id'], $item['options']);
		if(false !== $itemKey) {
			if($item['options'] == $this->_cartItems[$itemKey]['options']) {
				$this->_cartItems[$itemKey]['qty'] += $item['qty'];
			}
			else {
				$this->_cartItems[] = array(
					'id'      => $item['id'],
					'options' => $item['options'],
					'qty'     => $item['qty']
				);
			}
		}
		else {
			$this->_cartItems[] = array(
				'id'      => $item['id'],
				'options' => $item['options'],
				'qty'     => $item['qty']
			);
		}
		$this->_save();
	}

	private function _getItemKey($itemId, $options = false) {
		$itemKey = false;
        if (is_array($this->_cartItems)){
		foreach ($this->_cartItems as $key => $itemData) {
			if($itemId == $itemData['id']) {
				if($options) {
					if($itemData['options'] == $options) {
						$itemKey = $key;
					}
					else {
						continue;
					}
				}
				else {
					$itemKey = $key;
				}
				break;
			}
		}
        }
		return $itemKey;
	}

	public function getItems() {
		return $this->_cartItems;
	}

	public function removeItem($itemId, $options = false) {
		$itemKey = $this->_getItemKey($itemId, $options);
		if(false !== $itemKey) {
			unset ($this->_cartItems[$itemKey]);
			$this->_save();
		}
		return $this->_cartItems;
	}

	public function cleanCart() {
		$this->_cartItems = array();
		$this->_save();
	}

	public function increaseItemNumber($itemId, $number, $options = false) {
		//var_dump($options); die();
		$itemKey = $this->_getItemKey($itemId, $options);
		if(false !== $itemKey) {
			$this->_cartItems[$itemKey]['qty'] += $number;
			$this->_save();
			return true;
		}
		return false;
	}

	public function decreaseItemNumber($itemId, $number, $options = false) {
		$itemKey = $this->_getItemKey($itemId, $options);
		if(false !== $itemKey) {
			$this->_cartItems[$itemKey]['qty'] -= $number;
			if($this->_cartItems[$itemKey]['qty'] <= 0) {
				$this->removeItem($itemId, $options);
			}
			$this->_save();
			return true;
		}
		return false;
	}
    public function setItemQuantity($itemId, $quantity, $options = false){
        $itemKey = $this->_getItemKey($itemId, $options);
        if (false !== $itemKey) {
            $this->_cartItems[$itemKey]['qty'] = $quantity;
            $this->_save();
            return true;
        }
        return false;
    }

	public function getProductsList() {
		if(empty ($this->_cartItems)) {
			return array();
		}
		foreach ($this->_cartItems as $key => $productData) {
			$product = new RCMS_Object_Product_Product($productData['id']);
			$products[] = array(
				'id'           => $productData['id'],
				'count'        => $productData['qty'],
				'photo'        => $product->getPhoto(),
				'name'         => $product->getName(),
				'price'        => $product->getPrice(),
				'options'      => $productData['options'],
				'pricePerProd' => $product->getPrice() * $productData['qty'],
				'itemId'       => $product->getItemId(),
				'taxable'      => $product->getTax(),
				'weight'       => $product->getWeight()
			);
			$this->_totalPrice += isset($products['pricePerProd']) ? $products['pricePerProd'] : 0;
			$this->_totalWeight += isset($products['weight']) ? $products['weight'] * $productData['qty'] : 0;
			unset ($product);
		}
		return $products;
	}

    public function getFreebiesList() {
        if (empty ($this->_cartItems)){
            return array();
        }
        $return = array();
        foreach ($this->_cartItems as $key => $productData) {
            $product = new RCMS_Object_Product_Product($productData['id']);
            $freeIds = $product->getFreebies();
            unset($product);
            if ($freeIds != ''){
                foreach (explode(',',$freeIds) as $id){
                    $freebie = new RCMS_Object_Product_Product($id);
                    $return[$productData['id']][] = array(
                        'id'            => $freebie->getId(),
                        'count'         => $productData['qty'],
                        'photo'         => $freebie->getPhoto(),
                        'name'          => $freebie->getName(),
                        'price'         => '0',
                        'options'       => array(),
                        'itemId'        => $freebie->getItemId(),
                        'taxable'       => '0',
                        'weight'        => $freebie->getWeight(),
                        'note'          => '{%free%}',
                        'parent'        => $productData['id']
                    );
                    unset($freebie);
                }
            }
        }
        return $return;
    }

	public function getTaxableItemsData() {
		$data = array();
		if(empty($this->_cartItems)) {
			return array();
		}
		foreach ($this->_cartItems as $key => $productData) {
			$product = new RCMS_Object_Product_Product($productData['id']);
			if($product->getTax()) {
				$data[] = array(
					'id'           => $productData['id'],
					'price'        => $product->getPrice(),
                    'pricePerProd' => $product->getPrice() * $productData['qty'],
					'taxCategory'  => $product->getTax()
				);
			}
		}
		
		return $data;
	}

    /**
     * Returns total price of all items of Shopping Cart w/ or w/o taxes
     * @param <boolean> $withTaxes - include taxes or not
     * @param <array> $taxRule - tax rule
     * @return <integer>
     */
	public function getTotalPrice($withTaxes = false, $taxRule = null) {
		if(!$this->_totalPrice) {
			if(!empty($this->_cartItems)) {
				foreach ($this->_cartItems as $key => $producData) {
					$product = new RCMS_Object_Product_Product($producData['id']);
                    if ($withTaxes && !empty ($taxRule)){
                        $this->_totalPrice += ( $product->getPrice() + ($product->getPrice()*$taxRule['tax'][$product->getTax()])/100 )* $producData['qty'];
                    } else {
                        $this->_totalPrice += $product->getPrice() * $producData['qty'];
                    }
				}
			}
			else {
				$this->_totalPrice = 0;
			}
		}
		return $this->_totalPrice;
	}

	public function getItemsCount($itemId = false, $options = false) {
		$count = 0;
		if($itemId) {
			$itemKey = $this->_getItemKey($itemId, $options);
			$count = (false !== $itemKey) ? $this->_cartItems[$itemKey]['qty'] : 0;
		}
		else {
			foreach ($this->_cartItems as $key => $productData) {
				$count += $productData['qty'];
			}
		}
		return $count;
	}
    
    public function getTotalWeight(){
        if (!$this->_totalWeight){
            if (!empty ($this->_cartItems)) {
                foreach ($this->_cartItems as $cartItem) {
                    $product = new RCMS_Object_Product_Product($cartItem['id']);
                    $this->_totalWeight += ($product->getWeight()?$product->getWeight():0) * $cartItem['qty'];
                }
                //adding weight of freebies
                $freebies = $this->getFreebiesList();
                if (!empty($freebies)){
                    foreach ($freebies as $freebie){
                        $this->_totalWeight += $freebie['weight']*$freebie['count'];
                    }
                }
            } else {
                $this->_totalWeight = 0;
            }
        }
        return $this->_totalWeight;
    }

	public function getItemsCountForCart() {
		$count = 0;
        if (is_array($this->_cartItems)){
		foreach ($this->_cartItems as $key => $productData) {
			$count += $productData['qty'];
		}
        }
		return $count;
	}

	private function _save() {
		$this->_session->toasterShopingCartItems = serialize($this->_cartItems);
	}

	private function _load() {
		$this->_cartItems = unserialize($this->_session->toasterShopingCartItems);
	}
}